/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.yokeyword.fragmentation.extensions;

import ohos.aafwk.ability.fraction.Fraction;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/*
* Wrapper support setArguments and BackStack record
* */


public class FractionBackStack extends Stack<FractionEx> {
    public FractionEx getFractionExByTag(String tag) {
        FractionEx fe;
        for (int i = 0; i < size(); i++) {
            fe = get(i);
            if (fe.tag.equals(tag)) {
                return fe;
            }
        }
        return null;
    }

    public FractionEx findFractionByTag(String targetTag) {
        return getFractionExByTag(targetTag);
    }

    public FractionEx findActiveFractionEx(Fraction fraction) {
        FractionEx fe;
        for (int i = 0; i < size(); i++) {
            fe = get(i);
            if (fe.getActive() && (fe.getFraction() == fraction)) {
                return fe;
            }
        }
        return null;
    }

    public List<FractionEx> getActiveFractions() {
        ArrayList<FractionEx> result = new ArrayList<>();
        for (int i = 0; i < size(); i++) {
            if (get(i).getActive()) {
                result.add(get(i));
            }
        }
        return result;
    }

    public void removeDummyEntries() {
        for (int i = size()-1; i >= 0; i--) {
            if (!get(i).getActive()) {
                remove(get(i));
            }
        }
    }

    public FractionEx checkNewRecordOrAdd(Fraction fraction) {
        if (fraction == null)
            return null;
        FractionEx fe;
        for (int i = 0; i < size(); i++) {
            fe = get(i);
            if (fe.getFraction() == fraction)
                return fe;
        }
        return push(new FractionEx(fraction));
    }
}
